<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<%@include file="/WEB-INF/taglibs/common/taglibs.jsp"%>
<head>
<title><spring:message code="admin.createbonus.title" /></title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<link rel="stylesheet" href='<c:url value="/css/styles.css"/>' />
<script src='<c:url value="/javascripts/common.js"/>' type=""></script>

<script language="javascript" type="text/javascript">
var f = null;
var formulaeSize = 0;
var tmpValues = [];
var roles = [];
var users = [];
var tableColumns = {};
<c:forEach items="${tableList}" var="table">
<c:set var="columnList" value="${tableMap[table]}"></c:set>
tableColumns["${table}"] = [];
   <c:forEach items="${columnList}" var="col">
      tableColumns["${table}"].push("${col}");
   </c:forEach>
</c:forEach>
function selectTable()
{   var f = document.getElementById('bonus');
	var t = f.tableName;
	
	var tName = t[t.selectedIndex].value;
    var arr   = tableColumns[tName]; 
	var e = f.columnName;
	e.length = 0;

	for(var i=0;i<arr.length;i++)
	   {
  		  e.length  = e.length+1;
  		  e[i].text =  e[i].value = arr[i];
	   }    
   
	
}
function initForm()
{
  f = document.getElementById('bonus');
  f.operator[0].text = "Less Than";
  f.operator[0].value = "<";
  f.operator[1].text = "Greater Than";
  f.operator[1].value = ">";
  writeRolesAndUsers(); 
}
 
function setFormulaeSize(rowNum)
{   formulaeSize = rowNum;
	writeFormulaeTable(rowNum);	 
}
function saveTmpValues(){
	var f = document.getElementById('bonus');
	tmpValues = new Array();
	for(var i=0;i<formulaeSize;i++){
		tmpValues[i] = {"desiredAmount":f["desiredAmount"+i].value,
				        "displayRate":f["displayRate"+i].value 
			 			};
	   } 
}
function loadTmpValues(){
	var f = document.getElementById('bonus');
	for(var i=0;i<formulaeSize;i++){
		if(i > tmpValues.length-1)
	      {return;} 
		f["desiredAmount"+i].value = tmpValues[i].desiredAmount;
		f["displayRate"+i].value = tmpValues[i].displayRate;	
	   } 
}
function add(){
	saveTmpValues();
	setFormulaeSize(formulaeSize+1);
	updateFormulae();
	loadTmpValues();
}
function remove(num){ 
	saveTmpValues();
	if(formulaeSize == 1)
      {alert("Unnable to delete. \n In order to create a bonus , you need to enter at least one formulae.");return;}
	else
	  { 
	    var arr = []; 
	    for(var i=0;i<formulaeSize;i++)
	        {
 				if(i!=num) 
 	 			  arr.push(tmpValues[i]); 
	        }
		tmpValues = arr;
	  }
	setFormulaeSize(formulaeSize-1);
	updateFormulae();
	loadTmpValues();
}
function updateFormulae(){
		 var f = document.getElementById('bonus');
		 if(formulaeSize==0){
			 setFormulaeSize(formulaeSize+1);
		 }
		 //document.getElementById('condition'+i).innerHTML = "123";
		 for(var i=0;i<formulaeSize;i++){
             //document.getElementById('condition'+i).innerHTML = "123";
     document.getElementById('condition'+i).innerHTML = f.tableName[f.tableName.selectedIndex].value +"."+ f.columnName[f.columnName.selectedIndex].value;
     
     document.getElementById('operatorTxt'+i).innerHTML = "<i>"+f.operator[f.operator.selectedIndex].text +"</i>";

     document.getElementById('payType'+i).innerHTML = "<i>("+f.typeId[f.typeId.selectedIndex].text +")</i>";
            }
        
		
	
}

function writeFormulaeTable(rowNum){ 
 var t  = document.getElementById("fomulaeDivTemplate").innerHTML; 
 //alert(t);ccc
 var p1 = t.substring(0,t.indexOf('<tr>')); 
 var tr = t.substring(t.indexOf('<tr>'),t.indexOf('</table>')); 
 var p2 = t.substring(t.indexOf('</table>')); 

 var target = document.getElementById("fomulaeDiv");

 var html = ""+p1;
 var regExp = /_num/g;
 for(var i=0;i<rowNum;i++){
	 
	 html += tr.replace( regExp , i+"");
	 }
 
 
 html+=p2;
 target.innerHTML = html;
 
 document.getElementById('addRemoveDiv'+(rowNum-1)).style.display = 'inline';
 //if(rowNum>0)
  //{ document.getElementById('addRemoveDiv'+(rowNum-1)).style.display = 'inline';}
 
}

//--------------------------------------------------------------------------------
var popup = null;
function selectRoles(){

if(popup != null)
   popup.close();
	
popup = window.open('bonus_select_roles.htm','bonusSelectRoles','width=800,height=600'); 
}

function setRolesAndUsers( _roles , _users ){
	roles = [];
	users = [];

	//alert('setRolesAndUsers'+_roles.length+","+_users.length);

    for(var i=0;i<_roles.length;i++){
         var r = _roles[i];
         
    	 roles[i] = {"id"  :r.id+"",
    	    	     "name":r.name+""
        	    	}; 
        }

    for(var i=0;i<_users.length;i++){
        var u = _users[i];
        
   	 users[i] = {"id"  :u.id+"",
   	    	     "email":u.email+""
       	    	}; 
       }
    writeRolesAndUsers();
	
}

function writeRolesAndUsers(){
  var s = '';  
	if( roles.length==0 && users.length ==0)
	  {s = 'No Roles/Users selected.';}
	else
	  {
         for(var i=0;i<roles.length;i++){
  			  s+= roles[i].name+"<br>";
             }
         for(var i=0;i<users.length;i++){
 			  s+= users[i].email+"<br>";
            }
	  }  

	document.getElementById('rolesDiv').innerHTML = s;  
	
}

function save(){
	var f = document.getElementById('bonus');
  var desiredAmts = '';
  var rates = '';
  	
  for(var i=0;i<formulaeSize;i++){
	     desiredAmts += f['desiredAmount'+i].value+',';
	     rates		 += f['displayRate'+i].value+',';
	  }

  if(formulaeSize>0){
	  desiredAmts = desiredAmts.substring(0,desiredAmts.length-1);
	  rates       = rates.substring(0,rates.length-1);
	  }

  var rateElement = (f.typeId.selectedIndex==0)?f.flatRates:f.percentRates;
   
  f.desiredAmounts.value = desiredAmts;

  f.flatRates.value = f.percentRates.value = '';
  rateElement.value = rates;

 var r = '';
 var u = '';
 for(var i=0;i<roles.length;i++){
      r += roles[i].id+','; 
  }
 for(var i=0;i<users.length;i++){
     u += users[i].id+','; 
 }

 if(roles.length>0)
   	r = r.substring(0,r.length-1);	

 if(users.length>0)
   u = u.substring(0,u.length-1);  

  f.roleIds.value = r;
  f.userIds.value = u;
  
	
}

function loadData(){
	var f = document.getElementById('bonus');
	<c:if test="${mode != 'Create'}">
		<c:if test="${bonus.methodId == 1}"> 
		    switchMethod(${bonus.methodId});	     
		    f.methodId[0].checked = true; 
		    setFormulaeSize( ${fn:length(bonus.details.desiredAmounts)} );
		    updateDropdown(f.tableName,'${bonus.tableName}');
		    selectTable();
		    updateDropdown(f.columnName,'${bonus.columnName}');
		 </c:if>
		
		 <c:if test="${bonus.methodId == 2}"> 
		    switchMethod(${bonus.methodId});
		    f.methodId[1].checked = true; 
		    updateDropdown(f.payUnit,'${bonus.payUnit}');
		 </c:if>
	  <c:forEach var="r" items="${bonus.details.desiredAmounts}" varStatus="i">
	     f.desiredAmount${i.index}.value = '${r}';
	  </c:forEach>

	  <c:if test="${bonus.typeId == 1}">
	  <c:forEach var="r" items="${bonus.details.flatRates}" varStatus="i">
	     f.displayRate${i.index}.value = '${r}';
	  </c:forEach>
	  </c:if>

	  <c:if test="${bonus.typeId == 2}">
	  <c:forEach var="r" items="${bonus.details.percentRates}" varStatus="i">
	     f.displayRate${i.index}.value = '${r}';
	  </c:forEach>
	  </c:if>

	  

      
	  <c:forEach var="r" items="${bonus.roles}" varStatus="i">
	    roles[roles.length] = {"id":"${r.id}","name":"${r.name}"};
	  </c:forEach>

	  <c:forEach var="r" items="${bonus.users}" varStatus="i">
	    users[users.length] = {"id":"${r.id}","email":"${r.email}"};
	  </c:forEach>

	  updateDropdown(f.typeId,'${bonus.typeId}');
	  updateDropdown(f.operator,'${bonus.operator}');
	  updateDropdown(f.methodId,'${bonus.methodId}');	

	  updateFormulae();
	  writeRolesAndUsers();
	  
	</c:if>
	
}

function create(){
	if(!validateForm())return;
 //f.action = "create_bonus.htm";
 //document.location.href = 'create_bonus.htm';
 //this.form.action = "create_bonus.htm";
 var f = document.getElementById('bonus');
 f.action = "create_bonus.htm";
 save();
 f.submit(); 
}
function update(){ 
	 var f = document.getElementById('bonus');
	 f.action = "edit_bonus.htm";
	 save();
	 f.submit(); 
}
function updateDropdown(e,val){
	for(var i=0;i<e.length;i++)
	  {
   		 if(e[i].value == val)
   		   {e.selectedIndex = i;break;}
	  }
}

//--------------------------------
function switchMethod( mId ){

	var f = document.getElementById('bonus');
  	var on  = document.getElementById('amountDiv');
 	var off = document.getElementById('rowDiv');	
  
  if(mId == "2"){
	  on  = document.getElementById('rowDiv');
	  off = document.getElementById('amountDiv');

	  //we need these values for method 2
	  f.typeId.selectedIndex = 0;
	  if(f.providerCount.value.length==0)  
	  	f.providerCount.value = 0;
	  	
	  if(f.customerCount.value.length==0)	
      	f.customerCount.value = 0;

	  if(f.transactionCount.value.length==0)  	
     	 f.transactionCount.value = 0;

	  //we dont need these value for method 2
	  setFormulaeSize(1);	
	  f.desiredAmount0.value = f.displayRate0.value = '';
	  f.tableName.selectedIndex = 0;
	  selectTable();
	   //f.tableName.value = f.columnName.value = '';
  }
  else{
	  //reset unneeded fields to empty values
	  f.providerCount.value = f.customerCount.value = f.transactionCount.value = '';
	  f.payPerUnit.value = '';
	  f.payUnit.selectedIndex = 0;
  } 

  off.style.display = 'none';
  on.style.display  = 'inline';
	
}

//pay functions
function pay(bonusId){
 document.location.href = 'pay_bonus.htm?id='+id;	
}

function payOn(bonusId){
	// document.location.href = 'pay_bonus.htm?id='+id;	
	}

function payWhen(bonusId){
	// document.location.href = 'pay_bonus.htm?id='+id;	
	}

</script>

<script language="javascript">
// script added by Umme Essa. The form should be validated on all operations.
	 function validateForm(){
		return (validate_required(document.getElementById("name"),'Please enter bonus name.'));
	 }	
		 
	 </script>
</head>

<body onload="loadData();"><%@include file="../top_menu.jsp"%>
<table width=100%>
	<tr>
		<td><c:import url="/WEB-INF/jsp/menu/admin_bonus_menu.jsp" /><br />
		</td>
	</tr>
	<tr>
		<td><%@include file="/WEB-INF/jsp/include/messages.jsp"%>
		<br />
		</td>
	</tr>
</table>
<form:form commandName="bonus" method="post">
	<table width=70% class="formTable">

		<tr class="formHeader">
			<td colspan="5">${mode} <spring:message code="admin.createbonus.label.bonus" /></td>
		</tr>

		<c:if test="${bonus.id!=null}">
			<form:hidden path="id" />
		</c:if>
		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.bonusname" /></td>
			<td width="80%"><form:input path="name" size="30"
				readonly="false" /></td>

		</tr>

		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.description" /></td>
			<td width="80%"><form:input path="description" size="30"
				readonly="false" /></td>
		</tr>

		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.active" /></td>
			<td width="80%"><form:checkbox path="active" /></td>
		</tr>

		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.type" /></td>
			<td width="80%"><input type="radio" name="methodId"
				checked="checked" onclick="switchMethod(this.value);" value="1" /><spring:message code="admin.createbonus.label.useprincipleamount" /> <input type="radio" name="methodId"
				onclick="switchMethod(this.value);" value="2" /><spring:message code="admin.createbonus.label.usenumberofrows" /></td>
		</tr>

	</table>
	<div id="amountDiv" style="display: inline">
	<table id="m1Table" width=70% class="formTable">

		<tr class="formHeader">
			<td colspan="2"><spring:message code="admin.createbonus.label.amountdetails" /></td>
		</tr>
		<tr>

			<td width="18%"><spring:message code="admin.createbonus.label.principleamountmapping" /></td>
			<td width="80%"><spring:message code="admin.createbonus.label.table" /> <!--  form:input path="tableName" size="20" onchange="updateFormulae();" onkeypress="updateFormulae();"/ -->
			<form:select path="tableName"
				onchange="selectTable();updateFormulae();">
				<c:forEach items="${tableList}" var="item" varStatus="i">
					<form:option value="${item}">${item}</form:option>
				</c:forEach>
			</form:select> <spring:message code="admin.createbonus.label.column" /> <!--  <form:input path="columnName" size="20" onchange="updateFormulae();" onkeypress="updateFormulae();"/> -->
			<form:select path="columnName" onchange=" updateFormulae();">
				<form:option value="${bonus.columnName}">${bonus.columnName}</form:option>
			</form:select></td>
		</tr>

		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.operator" /></td>
			<td width="80%"><select name="operator"
				onchange="updateFormulae();">
				<option value="&lt;" selected="selected"><spring:message code="admin.createbonus.option.lessthan" /></option>
				<option value="&gt;"><spring:message code="admin.createbonus.option.greaterthan" /></option>
				<option value="="><spring:message code="admin.createbonus.option.equal" /></option>
				<option value="!="><spring:message code="admin.createbonus.option.notequal" /></option>
			</select></td>
		</tr>



		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.payas" /></td>
			<td width="80%"><select name="typeId"
				onchange="updateFormulae();">
				<option value="1"><spring:message code="admin.createbonus.option.fixedrate" /></option>
				<option value="2"><spring:message code="admin.createbonus.option.percentage" /></option>
			</select></td>
		</tr>

		<tr bgcolor="#FFFFFF">
			<td width="18%"><spring:message code="admin.createbonus.label.fomulae" /></td>
			<td width="80%">
			<div id="fomulaeDivTemplate" style="display: none">
			<table>
				<tr>
					<td><spring:message code="admin.createbonus.label.if" /></td>
					<td>
					<div id="condition_num"></div>
					</td>
					<td>
					<div id="operatorTxt_num" style="display: inline"></div>
					</td>
					<td><input type="text" size="5" name="desiredAmount_num"></input></td>
					<td><spring:message code="admin.createbonus.label.thenpay" /></td>
					<td><input type="text" name="flatRate_num" size="5"
						style="display: none" /> <input type="text"
						name="percentRate_num" size="5" style="display: none" /> <input
						type="text" name="displayRate_num" size="5"
						style="display: inline" /> <font id="payType_num"
						style="display: inlune"><spring:message code="admin.createbonus.label.paytype" /></font>
					<div id="addRemoveDiv_num" style="display: inline"><input
						type="button" class='ui-button ui-state-default ui-corner-all' value="<spring:message code="admin.createbonus.button.add" />" onclick="add();" /> <input
						type="button" class='ui-button ui-state-default ui-corner-all' value="<spring:message code="admin.createbonus.button.remove" />" onclick="remove(_num);" /></div>
					</td>
				</tr>

			</table>
			</div>
			<div id="fomulaeDiv" style="display: inline"></div>

			<div id="fomulaeForm" style="display: none">
			<hr></hr>
			<spring:message code="admin.createbonus.label.fomulaeform" />:<br></br>
			<spring:message code="admin.createbonus.label.desiredamounts" /> : <input name="desiredAmounts" type="text"></input><br></br>
			<spring:message code="admin.createbonus.label.flatrates" /> : <input name="flatRates" type="text"></input><br></br>
			<spring:message code="admin.createbonus.label.percentrates" /> : <input name="percentRates" type="text"></input><br></br>
			<spring:message code="admin.createbonus.label.roles" /> : <input name="roleIds" type="text"></input><br></br>
			<spring:message code="admin.createbonus.label.users" /> : <input name="userIds" type="text"></input><br></br>
			</div>
			</td>
		</tr>
	</table>
	</div>

	<div id="rowDiv" style="display: none">

	<table id="m2Table" border="0" cellpadding="4" cellspacing="0"
		width="100%">
		<tr bgcolor="#FFFFFF">
			<td colspan="2"><b><spring:message code="admin.createbonus.label.if" />:</b></td>
		</tr>
		<tr>
			<td width="30%"><spring:message code="admin.createbonus.label.serviceprovidercount" /></td>
			<td><spring:message code="admin.createbonus.label.isatleast" /> <form:input path="providerCount" size="3"
				onchange="updateFormulae();" onkeypress="updateFormulae();" /></td>
		</tr>
		<tr>
			<td width="30%"><spring:message code="admin.createbonus.label.customercount" /></td>
			<td><spring:message code="admin.createbonus.label.isatleast" /> <form:input path="customerCount" size="3"
				onchange="updateFormulae();" onkeypress="updateFormulae();" /></td>
		</tr>
		<tr>
			<td width="30%"><spring:message code="admin.createbonus.label.transactioncount" /></td>
			<td><spring:message code="admin.createbonus.label.isatleast" /> <form:input path="transactionCount" size="3"
				onchange="updateFormulae();" onkeypress="updateFormulae();" /></td>
		</tr>
		<tr bgcolor="#FFFFFF">
			<td colspan="2"><b><spring:message code="admin.createbonus.label.then" />:</b></td>
		</tr>
		<tr>
			<td width="30%"><spring:message code="admin.createbonus.label.pay" /></td>
			<td><form:input path="payPerUnit" size="3"
				onchange="updateFormulae();" onkeypress="updateFormulae();" /> <spring:message code="admin.createbonus.label.per" />
			<select name="payUnit">
				<option value="Provider"><spring:message code="admin.createbonus.label.provider" /></option>
				<option value="Customer"><spring:message code="admin.createbonus.label.customer" /></option>
				<option value="Transaction"><spring:message code="admin.createbonus.label.transaction" /></option>
			</select></td>
		</tr>
	</table>
	</div>

	<table border="0" cellpadding="4" cellspacing="0" width="100%">
		<tr bgcolor="#FFFFFF">
			<td width="30%"><spring:message code="admin.createbonus.label.applyto" /></td>
			<td width="70%"><input type="button" class='ui-button ui-state-default ui-corner-all' value="<spring:message code="admin.createbonus.button.selectroles" />"
				onclick="selectRoles();" /><br></br>
			<div id="rolesDiv"></div>
			</td>
		</tr>
		<c:if test="${bonus.id == null}">
			<tr>
				<td><input type="submit" class='ui-button ui-state-default ui-corner-all' value="<spring:message code="admin.createbonus.button.createnewbonus" />"
					onclick="create();" /></td>
			</tr>
		</c:if>
		<c:if test="${bonus.id != null}">
			<c:if test="${mode == 'Clone'}">
				<tr>
					<td><input type="submit" class='ui-button ui-state-default ui-corner-all' value="<spring:message code="admin.createbonus.button.saveasnewbonus" />"
						onclick="create();" /></td>
				</tr>
			</c:if>
			<c:if test="${mode == 'Update'}">
				<tr>
					<td><input type="submit" class='ui-button ui-state-default ui-corner-all' value="<spring:message code="admin.createbonus.button.updatebonus" />"
						onclick="update();" /></td>
				</tr>
			</c:if>
		</c:if>
	</table>

</form:form><%@include file="/WEB-INF/jsp/include/footer.jsp"%>
</body>
</html>